<template>
	<div class="box">
		<!-- 头部搜索模块 -->
	      <headerSearch :selectObj="selectObject" :isShowAdd="menuFlag" :goSearchFc="searchClick" :addFun="addmMchine"/>
	    <!-- 中间表格模块 -->

		<BaseTable :data="cargotableData" :columns="cargotableDataColumns" :tableHeight="tableHeight" :pagination="false" :loading="loading"></BaseTable>
		<!-- 分页 -->
		<div class="page">
			<el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="totalNum" :current-page="pageNum"
			 :page-size="pageSize" :page-sizes="[10, 15, 30, 50]" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
		</div>

		<!-- 添加/编辑 机械用户 -->
		<el-drawer :title="addEditFlag?'新增机械额定载荷/型号':'编辑机械额定载荷/型号'" :visible.sync="addEditDrawer" direction="rtl" size="30%"
		 :before-close="handleClose">
			<el-form :model="form" :rules="formRules" ref="refForm" label-width="140px" style="padding:20px">
				<el-form-item label="机械额定载荷/型号" prop="maccNo">
					<el-input @input="form.maccNo = verifyfilter('charemach*', form.maccNo)" v-model="form.maccNo"></el-input>
				</el-form-item>
				<el-form-item label="是否可用" prop="flag">
					<el-radio-group v-model="form.flag">
						<el-radio label="0">可用</el-radio>
						<el-radio label="1">不可用</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="机械类型" prop="macTypeCode">
					<el-select filterable v-model="form.macTypeCode" placeholder="请选择机械类型" style="width:100%">
						<el-option :label="item.dictLabel" :value="item.dictValue" v-for="item in macClassList" :key="item.dictValue"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="机械排序" prop="sortNum">
					<el-input @input="form.sortNum = verifyfilter('digit', form.sortNum)" v-model="form.sortNum"></el-input>
				</el-form-item>
				<div class="demo-drawer__footer">
					<el-button size="small" type="primary" @click="submitForm()" :loading="machLoading">{{ machLoading ? '提交中 ...' : '保 存' }}</el-button>
				</div>
			</el-form>
		</el-drawer>
	</div>
</template>

<script>
	import { formatDate, isObjectValueEqual } from '@/libs/date'
	import BaseTable from '@/components/BaseTable'
	import headerSearch from './component/headerSearch'

	export default {
	  name: 'metadatamach',
	  components: {
	    BaseTable,
	    headerSearch
	  },
	  data() {
	    return {
	      menuFlag: false,
	      menuArr: [],
	      machLoading: false,
			  // 搜索框显示对象
		      selectObject: [
		        {
		          name: '请选择机械类型',
		          type: 'select',
		          modelName: 'macTypeCode',
		          selectData: this.mactypeList
		        },
		        {
		          name: '机械额定载荷/型号',
		          type: 'input',
		          modelName: 'maccNo'
		        }
		      ],
	      cargotableDataColumns: [{
	        prop: 'maccNo',
	        label: '机械额定载荷/型号'
	      },
	      {
	        prop: 'macTypeName',
	        label: '机械类型'
	      },
	      {
	        prop: 'flag',
	        label: '是否可用',
	        render(h, params) {
	          if (params.row.flag == '0') {
	            return h('el-tag', {
	              props: {
	                size: 'mini'
	              },
	              domProps: {
	                innerHTML: '可用'
	              }
	            })
	          }
	          return h('el-tag', {
	            props: {
	              size: 'mini',
	              type: 'success'
	            },
	            domProps: {
	              innerHTML: '不可用'
	            }
	          })
	        }
	      },
	      {
	        prop: 'createName',
	        label: '录入人'
	      },
	      {
	        prop: 'createTime',
	        label: '录入时间'
	      },
	      {
	        prop: 'sortNum',
	        label: '排序',
	        sortable: true
	      },
	      {
	        label: '操作',
	        align: 'center',
	        width: 100,
	        render: (h, params) => {
	          return h(
	            'div', {
	              class: 'btnClass'
	            },
	            [
	              h('el-button', {
	                props: {
	                  size: 'mini'
	                },
	                style: {
	                  marginRight: '10px'
	                },
	                domProps: {
	                  innerHTML: `<span style='color:#0B6CD6;display: ${this.menuArr.includes('机械型号按钮修改') ? 'block' : 'none'}'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>编辑</span></span>`
	                },
	                on: {
	                  click: () => {
	                    this.handleEdit(params.$index, params.row)
	                  }
	                }
	              })

	              // h('el-button', {
	              //   props: {
	              //     size: 'mini'
	              //   },
	              //   domProps: {
	              //     innerHTML:
	              //       "<i class='iconfont icon-tubiao_liebiaoshanchu' style='color:#DA2821'></i>删除"
	              //   },
	              //   on: {
	              //     click: () => {
	              //       click: this.handleDelete(params.row.id)
	              //     }
	              //   }
	              // })
	            ]
	          )
	        }
	      }
	      ],
	      cargotableData: [],
	      addEditFlag: true,
	      // 搜索表单
	      searchForm: {
	        macTypeCode: '', // 机械型号
	        maccNo: ''
	      },

	      // 添加机械用户
	      form: {
	        maccNo: '',
	        createBy: '',
	        flag: '0',
	        createTime: '',
	        updateBy: '',
	        macTypeName: '',
	        sortNum: '',
	        updateTime: '',
	        macTypeCode: '',
	        delFlag: '',
	        updateName: '',
	        createName: ''
	      },
	      formRules: {
	        sortNum: [{
	          required: true,
	          message: '请输入排序',
	          trigger: 'blur'
	        }],
	        macTypeCode: [{
	          required: true,
	          message: '请选择机械种类',
	          trigger: 'blur'
	        }],
	        flag: [{
	          required: true,
	          message: '请选择是否可选',
	          trigger: 'change'
	        }],
	        maccNo: [{
	          required: true,
	          message: '请输入机械型号',
	          trigger: 'blur'
	        }]
	      },
	      mactypeList: [], // 机械型号数据
	      totalNum: 0, // 总页数
	      pageSize: 15, // 当前每页显示多少数据
	      pageNum: 0, // 当前页码
	      addEditDrawer: false,
	      loading: false,
	      macClassList: [], // 分类
	      flagHint: false
	    }
	  },
	  watch: {
	    form: {
	      handler(newVal, oldVal) {
	        console.log(isObjectValueEqual(newVal, oldVal))
	        this.flagHint = isObjectValueEqual(newVal, oldVal)
	      },
	      deep: true
	    }
	  },
  async activated() {
	    var menuArr = []
	    var menuId = ''
	    if (localStorage.getItem('menuArr')) {
	      menuArr = JSON.parse(localStorage.getItem('menuArr'))
	    }
	    menuArr.map(item => {
	      item.children.map(v => {
	        if (window.location.href.includes(v.url)) {
	          menuId = v.id
	        }
	      })
	    })

	    if (menuId) {
	      this.menuArr = []
	      await this.$http.get(`/${this.$ServiceName}/api/external/sysmenubtn/listresourcebtnbyid?menuId=${menuId}`, { timeout: 30000 })
	        .then(res => {
	          res.data.data.map(item => {
	            this.menuArr.push(item.resourceName)
	          })

	          if (!this.menuArr.includes('机械型号按钮新增')) {
	            this.menuFlag = false
	          } else {
	            this.menuFlag = true
	          }
	        }).catch((error) => {})
	    }
    if (this.$store.state.app.searchResouce == 'menu') {
		       this.searchForm = {
	        macTypeCode: '', // 机械型号
	        maccNo: ''
	      }
		        // 机械列表
	      this.getMachineList()
	      // 机械型号
	      this.getmactypeList()
	      // 机械类型
	      this.getmacClassList()
		    }
	  },
	  computed: {
    tableHeight: function() {
      return this.$store.state.tableHeight
    }
  },
	  methods: {
	    // 获取机械信息列表
	    async getMachineList() {
	      this.loading = true
	      await this.$http.get(
	        `/${this.$ServiceName}/api/external/mmachine/query?startpage=${this.pageNum}&pagesize=${this.pageSize}`, {
	          params: this.searchForm
	        }
	      ).then(res => {
        this.cargotableData = res.data.data.pages
	        // 分页
	        this.pageNum = res.data.data.pageNum // 当前页
	        this.pageSize = res.data.data.pageSize // 每页多少
	        this.totalNum = res.data.data.totalNum
	        this.loading = false
	      }).catch(error => { this.loading = false })
	    },
	    // 查询
	    async searchClick(searchData) {
	      this.pageNum = 1
				 this.searchForm = Object.assign(this.searchForm, searchData);
	      this.getMachineList()
	    },

	    // 获取机械型号
	    async getmactypeList() {
	      const res = await this.$http.get(
	        `/${this.$ServiceName}/api/external/public/listdict?dicttype=MAC_TYPE`
	      )
	      this.mactypeList = res.data.data
	      this.selectObject[0].selectData = this.mactypeList;
	    },
	    // 获取机械类型
	    async getmacClassList() {
	      const res = await this.$http.get(
	        `/${this.$ServiceName}/api/external/public/listdict?dicttype=MAC_TYPE`
	      )
	      this.macClassList = res.data.data
	    },
	    // 添加机械
	    addmMchine() {
	      this.addEditFlag = true
	      this.addEditDrawer = true
	      this.machLoading = false
	      this.form = {
	        flag: '0'
	      }
	    },
	    // 提交form表单
	    submitForm() {
	      this.$refs['refForm'].validate(async valid => {
	        if (valid) {
	          this.machLoading = true
	          if (this.addEditFlag) {
	            delete this.form.updateTime
	            delete this.form.updateName
	            delete this.form.updateBy
	            delete this.form.createBy
	            this.macClassList.forEach(n => {
	              if (n.dictValue == this.form.macTypeCode) {
	                this.form.macTypeName = n.dictLabel
	              }
	            })
	            await this.$http.post(
	              '/${this.$ServiceName}/api/external/mmachine/add',
	              this.form
	            ).then(res => {
	              this.$message.success(res.data.msg)
	              this.addEditDrawer = false
	              this.getMachineList()
	              this.machLoading = false
	            }).catch(error => { this.machLoading = false })
	          } else {
	            delete this.form.createTime
	            delete this.form.updateTime
	            delete this.form.updateName
	            delete this.form.updateBy
	            delete this.form.createBy
	            delete this.form.createName
	            delete this.form.index

	            this.macClassList.forEach(n => {
	              if (n.dictValue == this.form.macTypeCode) {
	                this.form.macTypeName = n.dictLabel
	              }
	            })

	            await this.$http.put(
	              '/${this.$ServiceName}/api/external/mmachine/updateone',
	              this.form
	            ).then(res => {
	              this.addEditDrawer = false
	              this.$message.success(res.data.msg)
	              this.getMachineList()
	              this.machLoading = false
	            }).catch(error => { this.machLoading = false })
	          }
	        } else {
	          return false
	        }
	      })
	    },
	    // 添加机械验真提交form重置表单
	    resetAddForm() {
	      this.$refs['ruleAddForm'].resetFields()
	    },
	    // 根据修改机械数据
	    async handleEdit(index, row) {
	      this.form = JSON.parse(JSON.stringify(row))
	      this.addEditFlag = false
	      this.addEditDrawer = true
	      this.machLoading = false
	    },

	    // 删除确认
	    // async sub(codes) {
	    //   const res = await this.$http.delete(
	    //     `/${this.$ServiceName}/api/external/mmachine/delete/${codes}`
	    //   )
	    //   if (res.data.code == '0000') {
	    //     this.$message.success('删除成功！')
	    //     //重新获取数据
	    //     this.getMachineList()
	    //   }
	    // },

	    // 监听pageSize改变事件
	    async handleSizeChange(val) {
	      this.pageSize = val
	      this.getMachineList()
	    },
	    // 分页 监听页码值改变
	    async handleCurrentChange(val) {
	      this.pageNum = val
	      this.getMachineList()
	    },
	    // dilog 关闭询问
	    handleClose(done) {
	      if (this.flagHint) {
	        this.$confirm('您已修改了数据，确定是否关闭？')
	          .then(_ => {
	            done()
	          })
	          .catch(_ => {})
	      } else {
	        done()
	        this.$refs.refForm.resetFields()
	      }
	    }
	    // async handleDelete(id) {
	    //   const confirmRes = await this.$confirm(
	    //     '此操作将永久删除该数据, 是否继续?',
	    //     '提示',
	    //     {
	    //       confirmButtonText: '确定',
	    //       cancelButtonText: '取消',
	    //       type: 'warning'
	    //     }
	    //   ).catch(err => {})
	    //   if (confirmRes !== 'confirm') {
	    //     return this.$message.info('已经取消删除')
	    //   }
	    //   this.sub(id)
	    // }
	  }
	}
</script>

<style lang="less" scoped>
	/deep/ .el-button--primary {
		background-color: #338ce8;
		border-color: #338ce8;
	}

	// 查询表单start
	.search_form {
        border: 1px solid #ebeef5;
        border-bottom: 0;
		background-color: #fff;
		color: #303133;
		border-radius: 4px;
		font-size: 14px;
		color: #606266;
		height: 50px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 16px;

		.btn_search,
		.workCom {
			margin-left: 10px;
		}

		/deep/.el-input {
			width: 150px;
		}
	}

	// 查询表单end
	.page {
		background: #ffffff;
		border-radius: 4px 4px 0 0;
	}

	.box {
		background: #ffffff;
		border: 1px solid #e1e4eb;
		border-radius: 4px 4px 0 0;
		border-top: none;
	}

	/deep/ .el-drawer__header {
		// margin-bottom: 12px;
		height: 40px;
		line-height: 41px;
		padding: 0 16px;
		box-sizing: border-box;
		border-bottom: 1px solid gainsboro;
		margin-bottom: 0;
	}

	/deep/ .demo-drawer__footer {
		text-align: right;
		padding-right: 1rem;
		border-top: 1px solid #c8cfde;
		background-color: #f5f7fa;
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		line-height: 50px;
	}

	/deep/ .el-table .cell {
		white-space: nowrap;
	}

	/deep/ .el-pagination {
		text-align: right;
		padding: 10px 20px;
	}

	/deep/ .el-table th>.cell {
		font-family: PingFangSC-Semibold;
		font-size: 14px;
		color: #606266;
	}

	/deep/ .el-table .el-button:focus,
	.el-table .el-button:hover {
		background-color: #fff;
		border: 1px solid #e1e4eb;
	}

	/deep/ .el-table .el-button--mini {
		color: #1684f6;
		border-color: transparent;
		background: transparent;
	}

	/deep/ .el-table th {
		border-left: 1px solid #ebeef5;
	}

	/deep/ .el-table th:nth-child(1) {
		border-left: none;
	}

	/deep/ .el-table--striped .el-table__body tr.el-table__row--striped td {
		background: #f5f7fa;
	}

	/deep/.el-pagination.is-background .btn-next,
	/deep/ .el-pagination.is-background .btn-prev,
	/deep/ .el-pagination.is-background .el-pager li {
		background: #ffffff;
		border: 1px solid #e1e4eb;
		border-radius: 3px;
		border-radius: 3px;
	}

	/deep/ .el-drawer__open .el-drawer.rtl {
		background: #f5f7fa;
	}

	/deep/ .el-drawer__body {
		overflow-y: auto;
		padding-bottom: 50px;
	}

	.header {
		width: 100%;
		height: 41px;
		line-height: 41px;
		background-color: #fff;
		padding: 0 20px;
		box-sizing: border-box;
	}

	.relatedInstitutions /deep/ .el-drawer__open .el-drawer.rtl {
		width: 30% !important;
		background: #f5f7fa;
	}

	.headerspan {
		background: #ffffff;
		border-bottom: 1px solid #e1e4eb;
		line-height: 40px;
		padding-left: 1rem;
	}

	.headerspan-item {
		line-height: 40px;
		padding-left: 1rem;
		font-size: 14px;
		color: #606266;
		letter-spacing: 0;
	}

	.btn /deep/ .el-button--mini,
	.el-button--mini.is-round {
		padding: 7px 6px;
	}
	.box {
	    background: #ffffff;
	    border: 1px solid #e1e4eb;
	    border-radius: 4px 4px 0 0;
	    border-top: none;
	}
</style>
